package com.qf.dao.impl;

import com.qf.dao.AccountDao;
import com.qf.pojo.Account;
import com.qf.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @Description: 公用常量
 * @Data: 2022/8/31 10:07
 * @Pacakge: com.qf.dao
 * @ClassName: AccountDaoImpl
 * @Author: fan
 */
public class AccountDaoImpl implements AccountDao {
    private QueryRunner queryRunner;

    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }
    /**
     * 根据id查找账户信息
     * @param name
     * @return
     */
    public Account findAccountByName(String name) {
        try {
            List<Account> list = queryRunner.query(connectionUtils.getConnection(),"select * from account where name=?",new BeanListHandler<Account>(Account.class),name);
            if(list == null || list.size() == 0){
                return null;
            }
            if(list.size() > 1){
                throw new RuntimeException();
            }
            return list.get(0);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 修改账户信息
     * @param account
     */
    public void updateAccount(Account account) {
        String sql = "update account set money=? where name=?";
        try {
            queryRunner.update(connectionUtils.getConnection(),sql,account.getMoney(),account.getName());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
